/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from 'react';
import { Tabs, List, Spin, Input, message } from 'antd';
import styles from './index.less';
import { connect } from 'dva';
import { names } from '../../config';
import KbChildrenWrapper from '@/components/KbChildrenWrapper';
import KbModal from '@/components/KbModal';
import KbIcon from '@/components/KbIcon';
import Lib from '@/components/KbAddressEidtor/Lib';
import KbDropdown from '@/components/KbDropdown';
import { check } from '@/utils/patterns';

const { Item: ListItem } = List;
const { TabPane } = Tabs;
const { Search: InputSearch } = Input;

@connect(({ loading, source }) => ({
  list: source.branchBrand,
  getting: loading.effects['source/searchBranch'],
  authing: loading.effects['source/auth'],
}))
class Branch extends Component {
  static defaultProps = {
    onAdded: () => {},
  };
  constructor(props) {
    super(props);
    this.state = {
      mobile: '',
      selectedAddress: null,
      activeKey: 'phone',
      visible: false,
    };
    this.tips = [
      '申通快宝商家专用面单（原商家77面大）是申通网点通过快宝平台给商家客户提供的专用面单。无需一次性充值，打一单扣取一单的费用。如需使用，请在微掌柜账户中充值保证面单费用充足。每单的价格由网点设置。申请后如没通过审核，或者在网点列表中找不到您的签约网点，请和网点或快递员联系确认是否已开通该项服务。',
    ];
  }

  //   打开或关闭指定弹窗
  onTriggerModal = open => {
    this.setState(
      {
        visible: open,
      },
      () => {
        if (open) {
          this.onSearch();
        }
      }
    );
  };

  onSearch = value => {
    const { dispatch } = this.props;
    const { selectedAddress, activeKey, mobile } = this.state;
    let payload;
    if (activeKey === 'phone') {
      const courier_mobile = value || mobile;
      if (courier_mobile) {
        const { code, message: msg } = check('phone', courier_mobile);
        if (code > 0) {
          message.error(msg);
          return;
        }
        payload = {
          courier_mobile,
        };
      }
    } else {
      if (selectedAddress) {
        const { label: address } = selectedAddress;
        payload = {
          address,
        };
      }
    }
    dispatch({
      type: 'source/searchBranch',
      payload,
    });
  };

  // 改变地址数据
  onChange = (calllback, data) => {
    const { province, city, district, address } = data;
    this.setState(
      {
        selectedAddress: {
          label: `${province}${city}${district}${address}`,
          data,
        },
      },
      this.onSearch
    );
    calllback();
  };

  overlay = calllback => (
    <>
      <div className={styles.sender_lay}>
        <Lib type="send" onSelect={this.onChange.bind(this, calllback)} />
      </div>
    </>
  );

  // 搜索内容改变
  onInputChange = e => {
    const { value: mobile } = e.target;
    this.setState({
      mobile,
    });
  };

  // 授权
  onApply = item => {
    const { branchCode: branch_code } = item;
    const { dispatch, onAdded } = this.props;
    this.branch_code = branch_code;
    dispatch({
      type: 'source/auth',
      payload: {
        branch_code,
      },
      kind: 'branch',
    }).then(({ code }) => {
      if (code == 0) {
        this.onTriggerModal(false);
        onAdded();
        dispatch({
          type: 'source/getBranch',
        });
        //单号源设置页面，获取最新的下拉框数据
        dispatch({
          type:"setter/getOperatorOrderSourceList"
        })
      }
    });
  };

  renderItem = item => {
    const { authing } = this.props;
    return (
      <ListItem
        key={item.branchCode}
        actions={[
          <a>
            {authing && this.branch_code === item.branchCode && <KbIcon type="loading" />} 申请
          </a>,
        ]}
        onClick={this.onApply.bind(this, item)}
      >
        {item.branchName}
      </ListItem>
    );
  };

  // 切换当前激活
  onSwitchActive = activeKey => {
    this.setState({
      activeKey,
    });
  };

  render() {
    const { visible, selectedAddress, activeKey } = this.state;
    const { children, list, getting } = this.props;
    return (
      <>
        <KbChildrenWrapper className="pointer" onClick={this.onTriggerModal.bind(this, true)}>
          {children}
        </KbChildrenWrapper>
        <KbModal
          centered
          visible={visible}
          onCancel={this.onTriggerModal.bind(this, false)}
          title={names.branch.label}
          okText=""
          footer={
            <div className="kb-tips">
              <div className="kb-tips_title">提示</div>
              {this.tips.map((item, index) => (
                <div key={index} className="kb-tips_item">
                  {item}
                </div>
              ))}
            </div>
          }
        >
          <Tabs activeKey={activeKey} onChange={this.onSwitchActive}>
            <TabPane tab="快递员手机号" key="phone">
              <InputSearch
                onChange={this.onInputChange}
                maxLength={11}
                placeholder="输入申通快递员手机号匹配"
                onSearch={this.onSearch}
              />
            </TabPane>
            <TabPane tab="发件地址" key="address">
              <KbDropdown
                placeholder="请选择您用于申请的地址"
                value={selectedAddress}
                bar="更改"
                labelInValue
                style={{ width: '100%' }}
                overlay={this.overlay}
              />
            </TabPane>
          </Tabs>

          <div className={styles.list}>
            <Spin spinning={!!getting}>
              <List
                className="kb-list kb-list-select"
                bordered
                dataSource={list}
                renderItem={this.renderItem}
              />
            </Spin>
          </div>
        </KbModal>
      </>
    );
  }
}

export default Branch;
